package com.shark.manager.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.shark.commons.constants.BaseConst;
import com.shark.commons.context.SystemHelper;
import com.shark.commons.utils.CookieKit;
import com.shark.commons.web.BaseController;
import com.shark.commons.web.model.AjaxResponse;
import com.shark.manager.system.service.UserService;

@Controller
@RequestMapping("/admin")
public class MainController extends BaseController {

	@Autowired
	private UserService userService ;
	
	/**
	 * 后台登陆页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = {"", "login", "index", "index.jsp", "index.html"}, method=RequestMethod.GET)
	public String loginpage(HttpServletRequest request) {
		try {
			//获取用户账号Cookie
			String loginKey = CookieKit.getCookieValue(request, BaseConst.COOKIE_NAME_LOGIN_KEY) ;
			if(null != loginKey) {
				String decodeLoginKey = new String(Base64.decodeBase64(loginKey),"utf-8");
				String[] cookieValues = decodeLoginKey.split(":") ;
				if(cookieValues.length == 3) {
					request.setAttribute(BaseConst.COOKIE_NAME_ACCOUNT, cookieValues[0]);
					request.setAttribute(BaseConst.COOKIE_NAME_PASSWORD, cookieValues[1]);
					request.setAttribute(BaseConst.COOKIE_NAME_REMEMBER, true);
				} 
			}else {
				request.setAttribute(BaseConst.COOKIE_NAME_REMEMBER, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "/manager/login" ;
	}
	
	/**
	 * 后台管理主页
	 * @param request
	 * @return
	 */
	@RequestMapping(value= {"main", "mainpage"}, method=RequestMethod.GET)
	public String mainpage(HttpServletRequest request) {
		return "/manager/main" ;
	}
	
	/**
	 * 系统登录验证
	 * @param account
	 * @param password
	 * @param validateCode
	 * @return
	 */
	@RequestMapping(value="loginValid", method=RequestMethod.POST)
	@ResponseBody
	public AjaxResponse loginValid(String account, String password, String validateCode, boolean remember) {
		AjaxResponse ajaxResponse = this.userService.loginValid(account, password) ;
		
		if(remember) {
			saveCookie(account, password);
		} else {
			CookieKit.clearCookies(request, response, BaseConst.COOKIE_NAME_LOGIN_KEY);
		}
		return ajaxResponse ;
	}
	
	/**
	 * 退出系统
	 */
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public String logout() {
		SystemHelper.logout();
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/admin/login";
	}
	
	
	/**
	 * 找回密码
	 * @param email
	 * @param validateCode
	 * @return
	 */
	@RequestMapping(value="/iforgotPassword", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse iforgotPassword(String email, String validateCode, HttpSession session) {
		String kaptcha = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY) ;
		if(null == kaptcha) {
			return new AjaxResponse().fail("验证码过期，请刷新！") ;
		}
		if(kaptcha.equals(validateCode)) {
			return this.userService.iforgotPassword(email) ;
		} else {
			return new AjaxResponse().fail("验证码不正确！") ;
		}
		
	}
	
	/**
	 * 检查找回密码的链接地址是否正确
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value="/iforgotCheckLink/{digitalSignature}", method=RequestMethod.GET)
	public String iforgotCheckLink(@PathVariable String digitalSignature, Model model) {
		model.addAttribute("resp", this.userService.iforgotCheckLink(digitalSignature)) ;
		return "/manager/iforgot" ;
	}
	
	/**
	 * 密码找回的重设密码
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/iforgotByResetPassword", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse iforgotByResetPassword(Long id, String newPassword) {
		AjaxResponse ajaxResponse = this.userService.iforgotByResetPassword(id, newPassword);
		CookieKit.clearCookies(request, response, BaseConst.COOKIE_NAME_LOGIN_KEY);
		return ajaxResponse ;
	}
	
	/**
	 * 保存Cookie
	 * @param account
	 * @param password
	 */
	private void saveCookie(String account, String password) {
		String cookie = account+":"+password+":"+System.currentTimeMillis();
		//默认保存用户账号的Cookie
		Map<String, String> cookieParams = new HashMap<String, String>() ;
		cookieParams.put(BaseConst.COOKIE_NAME_LOGIN_KEY, Base64.encodeBase64URLSafeString(cookie.getBytes())); //Base64进行编码
		CookieKit.addCookies(response, cookieParams, 60 * 60 * 24 * 30);
	}
}
